package com.www.applyword.ui.my;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import androidx.core.content.FileProvider;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.lljjcoder.Interface.OnCityItemClickListener;
import com.lljjcoder.bean.CityBean;
import com.lljjcoder.bean.DistrictBean;
import com.lljjcoder.bean.ProvinceBean;
import com.lljjcoder.citywheel.CityConfig;
import com.lljjcoder.style.citypickerview.CityPickerView;
import com.www.applyword.Constants.Constants;
import com.www.applyword.R;
import com.www.applyword.base.BaseActivity;
import com.www.applyword.bean.LoginBean;
import com.www.applyword.bean.ResumeBean;
import com.www.applyword.event.EventConstants;
import com.www.applyword.event.MessageEvent;
import com.www.applyword.http.CallBack;
import com.www.applyword.http.HttpClient;
import com.www.applyword.utils.ImageUtil;
import com.www.applyword.utils.PhotoUtil;
import com.www.applyword.utils.SPUtil;
import com.www.applyword.utils.Utils;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * author : huang
 * date   : 2019/10/24 0024 15:22
 * version: 1.0
 */
public class PersonalActivity extends BaseActivity implements View.OnClickListener {
    @BindView(R.id.civ_head_photo)
    CircleImageView civHeadPhoto;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.tv_sex)
    TextView tvSex;
    @BindView(R.id.tv_birthday)
    TextView tvBirthday;
    @BindView(R.id.tv_city)
    TextView tvCity;
    @BindView(R.id.et_cm)
    EditText etCm;
    @BindView(R.id.tv_education)
    TextView tvEducation;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.tv_heig_education)
    TextView tvHeigEducation;
    @BindView(R.id.et_email)
    EditText etEmail;
    @BindView(R.id.et_qq)
    EditText etQq;
    @BindView(R.id.et_weixin)
    EditText etWeixin;

    OptionsPickerView pvOptions;
    private String typeName;
    //自行添加一些string
    private List<String> gradeData = new ArrayList<>();
    private Dialog dialog, dialogHead;
    private Uri imageUri;
    private Uri cropImageUri;

    /* 请求识别码 */
    public static final int CODE_GALLERY_REQUEST = 0xa0;
    public static final int CODE_CAMERA_REQUEST = 0xa1;
    public static final int CODE_RESULT_REQUEST = 0xa2;

    // 裁剪后图片的宽(X)和高(Y),480 X 480的正方形。
    public static int OUTPUT_X = 480;
    public static int OUTPUT_Y = 480;

    private File fileUri = new File(Environment.getExternalStorageDirectory().getPath() + "/photo.jpg");
    private File fileCropUri = new File(Environment.getExternalStorageDirectory().getPath() + "/crop_photo.jpg");
    private boolean flag;


    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.personal_activity);
        setTitle("基本信息");
        setRringTitle("保存");
        tv_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveInfo();
            }
        });
    }

    @Override
    protected void loadData() {
        ResumeBean.ResumeBasicBean  resumeBasic = (ResumeBean.ResumeBasicBean) getIntent().getSerializableExtra("resumeBasic");
        if (null != resumeBasic) {
            flag = true;
            ImageUtil.setImage(civHeadPhoto, resumeBasic.getResumeBasic_HeadImg());
            String year1 = Utils.getYear(System.currentTimeMillis());
            String year2 = resumeBasic.getResumeBasic_DateOfBirth().substring(0, 4);
            int year3 = Integer.valueOf(year1) - Integer.valueOf(year2);
            etName.setText(resumeBasic.getResumeBasic_UserName());
            etName.setSelection(resumeBasic.getResumeBasic_UserName().length());
            tvBirthday.setText(resumeBasic.getResumeBasic_DateOfBirth().split(" ")[0]);
            tvSex.setText(resumeBasic.getResumeBasic_Sex());
            tvCity.setText(resumeBasic.getResumeBasic_City());
            tvEducation.setText(resumeBasic.getResumeBasic_EducationalStatus());
            etPhone.setText(resumeBasic.getResumeBasic_Mobile());
            tvHeigEducation.setText(resumeBasic.getResumeBasic_HighestDiploma());
            etCm.setText(resumeBasic.getResumeBasic_Height());
        }
    }



    @OnClick({R.id.tv_sex, R.id.tv_birthday, R.id.tv_city, R.id.tv_education, R.id.tv_heig_education,R.id.ll_photo})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_photo:
                showHeadDialog();
                break;
            case R.id.tv_sex:
                showSex(1);
                break;
            case R.id.tv_birthday:
                typeName = "出生日期";
                showBirthDay();
              //  Utils.hideInput();
                break;
            case R.id.tv_city:
                showAddress();
                break;
            case R.id.tv_education:
                typeName = "教育状态";
                showSex(3);
             //   Utils.hideInput();
                break;
            case R.id.tv_heig_education:
                typeName = "学历";
                showSex(2);
                break;
                default:
        }
    }

    //保存
    private void saveInfo() {
        if (!flag) {
            Utils.showToastSafe("请上传头像");
            return;
        }
        if (TextUtils.isEmpty(etName.getText().toString().trim())) {
            Utils.showToastSafe("请填写姓名");
            return;
        }
        if (TextUtils.isEmpty(tvSex.getText().toString().trim())) {
            Utils.showToastSafe("请选择性别");
            return;
        }
        if (TextUtils.isEmpty(tvBirthday.getText().toString().trim())) {
            Utils.showToastSafe("请选择生日年份");
            return;
        }
        if (TextUtils.isEmpty(tvCity.getText().toString().trim())) {
            Utils.showToastSafe("请选择所在城市");
            return;
        }
        if (TextUtils.isEmpty(tvEducation.getText().toString().trim())) {
            Utils.showToastSafe("请选择教育状态");
            return;
        }
        if (!Utils.isPhoneNumber(etPhone.getText().toString())) {
            Utils.showToastSafe("请输入正确的手机号码");
            return;
        }
        if (TextUtils.isEmpty(tvHeigEducation.getText().toString().trim())) {
            Utils.showToastSafe("请选择最高学历");
            return;
        }

        HttpClient.postImg(PersonalActivity.this, Constants.UPLOADRESUME, fileCropUri, new CallBack<List<String>>() {
            @Override
            public void onSuccess(List<String> list) {
               String url = list.get(0);
                Map<String, Object> params = new HashMap<>();
                params.put("ResumeBasic_UserID", SPUtil.getString(Constants.USERID));
                params.put("ResumeBasic_HeadImg", Constants.HOST + url);
                params.put("ResumeBasic_Name",etName.getText().toString().trim());
                params.put("ResumeBasic_Sex", tvSex.getText().toString());
                params.put("ResumeBasic_DateOfBirth", tvBirthday.getText().toString());
                params.put("ResumeBasic_Height", etCm.getText().toString().trim());
                params.put("ResumeBasic_EducationalStatus", tvEducation.getText().toString());
                params.put("ResumeBasic_Mobile", etPhone.getText().toString().trim());
                params.put("ResumeBasic_HighestDiploma", tvHeigEducation.getText().toString().trim());
                params.put("ResumeBasic_MailBox", etEmail.getText().toString().trim());
                params.put("ResumeBasic_QQ", etQq.getText().toString().trim());
                params.put("ResumeBasic_WeChat", etWeixin.getText().toString().trim());
                params.put("ResumeBasic_City", tvCity.getText().toString().trim());
                HttpClient.post(PersonalActivity.this, Constants.RESUMEBASIC, params, new CallBack<LoginBean>() {
                    @Override
                    public void onSuccess(LoginBean result) {
                        MessageEvent messageEvent = new MessageEvent();
                        messageEvent.setMessageKey(EventConstants.DEL_RESUMESCHOOL);
                        EventBus.getDefault().post(messageEvent);
                        Utils.showToastSafe("保存成功");
                        finish();
                    }
                });
            }
        });
    }

    private void showHeadDialog() {
        dialogHead = new Dialog(this, R.style.ActionSheetDialogStyle);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_head_portrait, null);
        view.findViewById(R.id.dialog_shoot).setOnClickListener(this);
        view.findViewById(R.id.dialog_photo_album).setOnClickListener(this);
        view.findViewById(R.id.dialog_cancel).setOnClickListener(this);
        dialogHead.setContentView(view);
        Window window = dialogHead.getWindow();
        if (window == null) {
            return;
        }
        dialogHead.show();//显示对话框//设置Dialog从窗体底部弹出
        window.setGravity(Gravity.BOTTOM);
        //获取窗体的属性
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.y = 20;//设置Dialog距离底部的距离
        //将属性设置给窗体
        window.setAttributes(lp);
    }

    private void showBirthDay() {
        hideInput2();
        Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        startDate.set(1949,1,1);
        Calendar endDate = Calendar.getInstance();
        endDate.set(2030,1,1);

        TimePickerView pvTime =  new TimePickerBuilder(this, (date, v) -> tvBirthday.setText(Utils.getTime2(date)))
                .setType(new boolean[]{true, true, true, false, false, false})//默
                .setTitleText(typeName)
                .setSubmitText("确定")//确定按钮文字
                .setCancelText("取消")//取消按钮文字
                .setSubCalSize(10)//确定和取消文字大小
                .setSubmitColor(0xffFF6767)//确定按钮文字颜色
                .setCancelColor(0xff999999)//取消按钮文字颜色
                .setTitleBgColor(0xffF4F4F4)//标题背景颜色 Night mode
                .setTitleSize(10)
                .setContentTextSize(12)//滚轮文字大小
                .setTextColorCenter(0xff333333)
                .isCyclic(true)//是否循环滚动
                .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
                .setRangDate(startDate,endDate)//起始终止年月日设定
                .setTextColorOut(0x999999)
                .setDividerColor(0xffEEEEEE)
                .setLabel("年","月","日","时","分","秒")
                .setOutSideCancelable(true)//点击外部dismiss default true
                .isDialog(false)//是否显示为对话框样式
                .setLineSpacingMultiplier((float) 2.5) //设置item的高度
                .build();
        //注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
        pvTime.setDate(Calendar.getInstance());
        pvTime.show();
    }

    private void showAddress() {
        hideInput2();
        //申明对象
        CityPickerView mPicker=new CityPickerView();
        //预先加载仿iOS滚轮实现的全部数据（oncreate()中）
        mPicker.init(this);
        //配置
        CityConfig cityConfig = new CityConfig.Builder()
                .title("选择城市")//标题
                .titleTextSize(10)//标题文字大小
                .titleTextColor("#585858")//标题文字颜  色
                .titleBackgroundColor("#ffdddddd")//标题栏背景色
                .confirTextColor("#ffe1163c")//确认按钮文字颜色
                .confirmText("确定")//确认按钮文字
                .confirmTextSize(10)//确认按钮文字大小
                .cancelTextColor("#585858")//取消按钮文字颜色
                .cancelText("取消")//取消按钮文字
                .cancelTextSize(10)//取消按钮文字大小
                .setCityWheelType(CityConfig.WheelType.PRO_CITY_DIS)//显示类，只显示省份一级，显示省市两级还是显示省市区三级
                .showBackground(true)//是否显示半透明背景
                .visibleItemsCount(7)//显示item的数量
                .province("湖北省")//默认显示的省份
                .city("武汉市")//默认显示省份下面的城市
                .district("洪山区")//默认显示省市下面的区县数据
                .provinceCyclic(true)//省份滚轮是否可以循环滚动
                .cityCyclic(true)//城市滚轮是否可以循环滚动
                .districtCyclic(true)//区县滚轮是否循环滚动
                .setCustomItemLayout(R.layout.item_city)//自定义item的布局
                .setCustomItemTextViewId(R.id.item_city_name_tv)//自定义item布局里面的textViewid
                .drawShadows(false)//滚轮不显示模糊效果
                .setLineHeigh(1)//中间横线的高度
                .setLineColor("#fff9c21a")
                .setShowGAT(true)//是否显示港澳台数据，默认不显示
                .build();
        //添加配置
        mPicker.setConfig(cityConfig);
        //显示
        mPicker.showCityPicker();
        //监听选择点击事件及返回结果
        mPicker.setOnCityItemClickListener(new OnCityItemClickListener() {
            @Override
            public void onSelected(ProvinceBean province, CityBean city, DistrictBean district) {
                super.onSelected(province, city, district);
                //为TextView赋值
                tvCity.setText(province + "-" + city + "-" + district);
            }

            @Override
            public void onCancel() {
                super.onCancel();
            }
        });
    }


    private void showSex(int type) {
        hideInput2();
        if (type == 1){
            gradeData.clear();
            gradeData.add("男");
            gradeData.add("女");
        }else if (type == 2){
            gradeData.clear();
            gradeData.add("高中以下");
            gradeData.add("高中");
            gradeData.add("中专/技校");
            gradeData.add("大专");
            gradeData.add("本科");
            gradeData.add("硕士");
            gradeData.add("博士");
        }else if (type == 3){
            gradeData.clear();
            gradeData.add("在读");
            gradeData.add("已毕业");
        }else if (type == 4){
            gradeData.clear();
            gradeData.add("不限");
            gradeData.add("18-30岁");
            gradeData.add("30-40岁");
            gradeData.add("50岁以下");
        }
        pvOptions = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> {
            if (type == 1) {
                tvSex.setText(gradeData.get(options1));
            }else if (type == 2){
                //学历
                typeName = "学历";
                tvHeigEducation.setText(gradeData.get(options1));
            }else if (type == 3){
                tvEducation.setText(gradeData.get(options1));
            }else if (type == 4){

            }
        })
                .setTitleText(typeName)
                .setSubmitText("确定")//确定按钮文字
                .setCancelText("取消")//取消按钮文字
                .setSubCalSize(10)//确定和取消文字大小
                .setSubmitColor(0xffFF6767)//确定按钮文字颜色
                .setCancelColor(0xff999999)//取消按钮文字颜色
                .setTitleBgColor(0xffF4F4F4)//标题背景颜色 Night mode
                .setTitleSize(10)
                .setContentTextSize(12)//滚轮文字大小
                .setTextColorCenter(0xff333333)
                .setTextColorOut(0x999999)
                .setDividerColor(0xffEEEEEE)
                .setCyclic(false, false, false)//循环与否
                .setSelectOptions(0, 0, 0)  //设置默认选中项
                .setOutSideCancelable(true)//点击外部dismiss default true
                .isDialog(false)//是否显示为对话框样式
                .isRestoreItem(true)//切换时是否还原，设置默认选中第一项。
                .setLineSpacingMultiplier((float) 2.5) //设置item的高度
                .build();
        pvOptions.setPicker(gradeData);
        pvOptions.show();
    }

    private void hideInput2() {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        View v = getWindow().peekDecorView();
        if (null != v) {
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.dialog_shoot://拍摄
                imageUri = Uri.fromFile(fileUri);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    imageUri = FileProvider.getUriForFile(this, "com.whmnrc.parttimejob.FileProvider", fileUri);
                }
                PhotoUtil.takePicture(this, imageUri, CODE_CAMERA_REQUEST);
                dialogHead.dismiss();

                break;
            case R.id.dialog_photo_album://相册
                PhotoUtil.openPic(this, CODE_GALLERY_REQUEST);
                dialogHead.dismiss();
                break;

            case R.id.dialog_cancel://取消
                dialogHead.dismiss();
                break;

            default:
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case CODE_CAMERA_REQUEST:
                    cropImageUri = Uri.fromFile(fileCropUri);
                    PhotoUtil.cropImageUri(this, imageUri, cropImageUri, 1, 1, OUTPUT_X, OUTPUT_Y, CODE_RESULT_REQUEST);
                    break;
                case CODE_GALLERY_REQUEST:
                    cropImageUri = Uri.fromFile(fileCropUri);
                    Uri newUri = Uri.parse(PhotoUtil.getPath(this, intent.getData()));
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        newUri = FileProvider.getUriForFile(this, "com.whmnrc.parttimejob.FileProvider", new File(newUri.getPath()));
                    }
                    PhotoUtil.cropImageUri(this, newUri, cropImageUri, 1, 1, OUTPUT_X, OUTPUT_Y, CODE_RESULT_REQUEST);
                    break;
                case CODE_RESULT_REQUEST:
                    Bitmap bitmap = PhotoUtil.getBitmapFromUri(cropImageUri, this);
                    if (bitmap != null) {
                        flag = true;
                        civHeadPhoto.setImageBitmap(bitmap);
                    }
                    break;
                default:
            }
        }

        super.onActivityResult(requestCode, resultCode, intent);
    }
}
